package com.example.ordersservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.commonutils.handler.NoqueueException;
import com.example.commonutils.vo.OrderCustomerCommon;
import com.example.commonutils.vo.ShoppingCartCommon;
import com.example.ordersservice.client.CustomerClient;
import com.example.ordersservice.client.ShoppingCartClient;
import com.example.ordersservice.entity.OrderOrderdetail;
import com.example.ordersservice.entity.OrderOrders;
import com.example.ordersservice.mapper.OrderOrdersMapper;
import com.example.ordersservice.service.OrderOrderdetailService;
import com.example.ordersservice.service.OrderOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ordersservice.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-06-23
 */
@Service
public class OrderOrdersServiceImpl extends ServiceImpl<OrderOrdersMapper, OrderOrders> implements OrderOrdersService {

    @Autowired
    private CustomerClient customerClient;
    @Autowired
    private ShoppingCartClient shoppingCartClient;
    @Autowired
    private OrderOrderdetailService orderOrderdetailService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void batchDelete(List<String> ids) {
        LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderOrders::getId,ids);
        List<OrderOrders> orders = baseMapper.selectList(queryWrapper);
        //删除订单详情表的数据
        for (OrderOrders order : orders) {
            String ordersNumber = order.getOrdersNumber();
            LambdaQueryWrapper<OrderOrderdetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderOrderdetail::getOrdersNumber,ordersNumber);
            orderOrderdetailService.remove(queryWrapper1);
        }
        baseMapper.delete(queryWrapper);
    }

    @Override
    public OrderOrders createOrders(List<String> ids, String customerId, String notes) {
        if (ids.size()==0){
            throw new NoqueueException(20001,"请选择菜品");
        }
        //通过用户id查询用户信息
        //远程调用
        OrderCustomerCommon customer = customerClient.getCustomerInfoById(customerId);
        String username = customer.getUsername();
        String phone = customer.getPhone();
        //ids是购物车中选中的购物车数据的id
        String orderDetail = "";
        BigDecimal totalAmount = new BigDecimal(0.00);
        String orderNo = OrderNoUtil.getOrderNo();
        int totalDishTime = 0;
        for (String id : ids) {
            //通过id获取购物车中菜品的单价(service-ordermeal模块)
            //通过id获取购物车中该菜品的数量并计算出总价
            ShoppingCartCommon shoppingCartCommon = shoppingCartClient.queryShoppingCartInfo(id);
            //TODO 如果库存被改，导致顾客购物车的菜品数量大于库存数，则生成订单失败
            Integer cartDishNum = shoppingCartCommon.getCopies();
            String dishId = shoppingCartCommon.getDishId();
            //通过dishId查询菜品的库存
            Integer realDishNum = shoppingCartClient.queryDishNumById(dishId);
            if (cartDishNum > realDishNum){
                throw new NoqueueException(20001,"菜品库存不足");
            }
            //通过dishId查询菜品所需时间
            int time = shoppingCartClient.selectTime(dishId);
//            int timeSeconds = time * 60;
            String dishName = shoppingCartCommon.getDishName();
            BigDecimal subtotalAmount = shoppingCartCommon.getTotalAmount();
            Integer copies = shoppingCartCommon.getCopies();
//            int subDishTime = timeSeconds * copies;
            int subDishTime = time * copies;
            totalDishTime = totalDishTime + subDishTime;
            String dishNum = copies+";";
            String subOrderDetail  = dishName +"×"+ dishNum;
            totalAmount = totalAmount.add(subtotalAmount);
            orderDetail = orderDetail + subOrderDetail;
            //往订单详情表中插入数据
            OrderOrderdetail orderdetail = new OrderOrderdetail();
            orderdetail.setDishId(dishId);
            orderdetail.setOrdersNumber(orderNo);
            orderdetail.setDishNumber(copies);
            orderOrderdetailService.save(orderdetail);
        }
        OrderOrders orders = new OrderOrders();
        orders.setOrdersTime(totalDishTime);
        orders.setOrdersPhone(phone);
        orders.setOrdersName(username);
        orders.setOrdersDetails(orderDetail);
        orders.setOrdersAmount(totalAmount);
        orders.setOrdersNumber(orderNo);
        orders.setOrdersNotes(notes);
        orders.setOrdersStatus(3);
        baseMapper.insert(orders);
        return orders;
    }

    @Override
    public void countDown(String ordersNumber) throws InterruptedException {
        LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderOrders::getOrdersNumber,ordersNumber);
        OrderOrders orders = baseMapper.selectOne(queryWrapper);
        do {
            orders.setOrdersTime(orders.getOrdersTime()-1);
            baseMapper.updateById(orders);
            stringRedisTemplate.delete("cache:ordersAmount");
            Thread.currentThread().sleep(1000*60);
        }while (orders.getOrdersTime() > 0);
    }

    // 查询某一天的总交易额
    @Override
    public BigDecimal getTotalPayAmount(String date) {
        return baseMapper.getTotalPayAmount(date);
    }

    @Override
    public int getTotalNum(String date) {
        return baseMapper.getTotalNum(date);
    }
}
